package com.magiccompass.alipay.barcode.util;

import java.util.List;
import java.util.TreeMap;

import com.magiccompass.alipay.barcode.constants.AlipayPartnerConstants;
import com.magiccompass.alipay.barcode.constants.BusinessLogicConstants;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodeCancelRequest;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodePaymentRequest;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodeQueryRequest;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodeRefundRequest;
import com.magiccompass.alipay.barcode.entity.AlipayBarcodeReverseRequest;
import com.magiccompass.alipay.barcode.entity.AlipayQRCodeCreateRequest;
import com.magiccompass.alipay.barcode.entity.AlipayQRCodeNotification;
import com.magiccompass.alipay.barcode.entity.MerchantInfo;
import com.magiccompass.alipay.barcode.entity.MerchantTransaction;
import com.magiccompass.alipay.barcode.model.AlipayBarcodeBaseRequest;
import com.magiccompass.alipay.barcode.service.AlipayBarcodeService;
import com.magiccompass.alipay.barcode.service.AlipayBarcodeServiceImpl;
import com.magiccompass.alipay.barcode.signature.RSASignature;
import com.magiccompass.alipay.barcode.util.DateTimeUtil;

public class AlipayBarcodeRequestUtil {
	public static AlipayBarcodePaymentRequest alipayBarcodeRequestEntityInit(MerchantTransaction mt, String customerALIPAYBarcode, Integer operatorId){
		AlipayBarcodePaymentRequest abr = new AlipayBarcodePaymentRequest();
		abr.setBuyerIdentityCode(customerALIPAYBarcode);
		abr.setCreateBy(operatorId);
		//abr.setCreateTime();  // already in entity default value
		//abr.setCurrency(BusinessLogicConstants.CURRENCY);
		abr.setCurrency(mt.getMerchant().getDefaultCurrency());
		//abr.setDelFlag();  // already in entity default value
		abr.setIdentityCodeType(AlipayPartnerConstants.IDENTITY_CODE_TYPE);
		abr.setMerchant(mt.getMerchant());
		abr.setMerchantTransaction(mt);
		//abr.setStatus();  // already in entity default value
		abr.setTotalAmount(mt.getTotalAmount());
		abr.setTransName(BusinessLogicConstants.TRANS_NAME);
		abr.setExtendInfo(makePaymentReqestExtendInfo(mt));		
		return abr;
	}
	
	public static AlipayBarcodeCancelRequest alipayBarcodeCancelRequestEntityInit(MerchantTransaction mt, Integer operatorId){
		AlipayBarcodeCancelRequest abcr = new AlipayBarcodeCancelRequest();
		abcr.setCreateBy(operatorId);
		abcr.setMerchant(mt.getMerchant());
		abcr.setMerchantTransaction(mt);
		return abcr;
	}
	
	public static AlipayBarcodeReverseRequest alipayBarcodeReverseRequestEntityInit(MerchantTransaction mt, Integer operatorId){
		AlipayBarcodeReverseRequest abrr = new AlipayBarcodeReverseRequest();
		abrr.setCreateBy(operatorId);
		abrr.setMerchant(mt.getMerchant());
		abrr.setMerchantTransaction(mt);
		return abrr;
	}
	
	public static AlipayBarcodeRefundRequest alipayBarcodeRefundRequestEntityInit(MerchantTransaction mt, Integer operatorId){
		AlipayBarcodeRefundRequest abrr = new AlipayBarcodeRefundRequest();
		abrr.setCreateBy(operatorId);
		abrr.setMerchant(mt.getMerchant());
		abrr.setMerchantTransaction(mt);
		
		abrr.setCurrency(mt.getMerchant().getDefaultCurrency());
		abrr.setRefundAmount(mt.getTotalAmount());
		return abrr;
	}
	
	public static AlipayQRCodeCreateRequest alipayBarcodeCreateRequestEntityInit(MerchantInfo mi, Integer operatorId){
		AlipayQRCodeCreateRequest aqrccr = new AlipayQRCodeCreateRequest();
		aqrccr.setCreateBy(operatorId);
		aqrccr.setMerchant(mi);
		return aqrccr;
	}
	
	public static AlipayBarcodeQueryRequest alipayBarcodeQueryRequestEntityInit(MerchantTransaction mt, Integer operatorId){
		AlipayBarcodeQueryRequest abqr = new AlipayBarcodeQueryRequest();
		abqr.setCreateBy(operatorId);
		abqr.setMerchant(mt.getMerchant());
		abqr.setMerchantTransaction(mt);
		return abqr;
	}
	
	public static String getSign(TreeMap<String,String> parameterMap){
		String sign = makeAlipayBarcodeRequestSign(parameterMap);
		return sign;
	}
	
	public static String makeAlipayBarcodeRequestSign(TreeMap<String,String> parameterMap){
		String sign = null;
		try {
			sign = RSASignature.rsaSign(parameterMap, AlipayPartnerConstants.SELF_PRIVATE_KEY, AlipayPartnerConstants._INPUT_CHAR_SET);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sign;
	}
	
	public static TreeMap<String,String> makeParameterMap4Alipay(AlipayBarcodeBaseRequest abr, AlipayBarcodeService alipayBarcodeService){
		TreeMap<String,String> barcodeRequest4AlipayTreeMap = new TreeMap<String,String>();
		// basic parameter
		barcodeRequest4AlipayTreeMap.put("partner", AlipayPartnerConstants.PARTNER_ID);
		barcodeRequest4AlipayTreeMap.put("_input_charset", AlipayPartnerConstants._INPUT_CHAR_SET);

		if(abr instanceof AlipayBarcodePaymentRequest){
			// Operation parameter
			barcodeRequest4AlipayTreeMap.put("alipay_seller_id", AlipayPartnerConstants.PARTNER_ID);
			barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());

			AlipayBarcodePaymentRequest abpr = (AlipayBarcodePaymentRequest)abr;
			// barcodeRequest4AlipayTreeMap.put("quantity", "1");
			barcodeRequest4AlipayTreeMap.put("service", AlipayPartnerConstants.SERVICE_PAY);
			barcodeRequest4AlipayTreeMap.put("trans_name", abpr.getTransName());
			//barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getId().toString());
			barcodeRequest4AlipayTreeMap.put("currency", abpr.getMerchant().getDefaultCurrency());
			barcodeRequest4AlipayTreeMap.put("trans_amount", abpr.getTotalAmount().toString());
			barcodeRequest4AlipayTreeMap.put("buyer_identity_code", abpr.getBuyerIdentityCode());
			barcodeRequest4AlipayTreeMap.put("identity_code_type", AlipayPartnerConstants.IDENTITY_CODE_TYPE);
			barcodeRequest4AlipayTreeMap.put("trans_create_time", DateTimeUtil.getYYYYMMDDHH24MISSStringFromTimestamp(abpr.getCreateTime()) );
			barcodeRequest4AlipayTreeMap.put("biz_product", AlipayPartnerConstants.BIZ_CODE);
			barcodeRequest4AlipayTreeMap.put("extend_info", abpr.getExtendInfo());
		}else if(abr instanceof AlipayBarcodeCancelRequest){
			// Operation parameter
			barcodeRequest4AlipayTreeMap.put("alipay_seller_id", AlipayPartnerConstants.PARTNER_ID);
			if("Q".equals(abr.getMerchantTransaction().getType())){
				AlipayQRCodeNotification aqrn = alipayBarcodeService.findAlipayQRCodeNotificationByMTId(abr.getMerchantTransaction().getId());
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", aqrn.getOutTradeNo());				
			}else if("B".equals(abr.getMerchantTransaction().getType())){
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}else{
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}
			barcodeRequest4AlipayTreeMap.put("service", AlipayPartnerConstants.SERVICE_CANCEL);
		}else if(abr instanceof AlipayBarcodeReverseRequest){
			// Operation parameter
			barcodeRequest4AlipayTreeMap.put("alipay_seller_id", AlipayPartnerConstants.PARTNER_ID);
			if("Q".equals(abr.getMerchantTransaction().getType())){
				AlipayQRCodeNotification aqrn = alipayBarcodeService.findAlipayQRCodeNotificationByMTId(abr.getMerchantTransaction().getId());
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", aqrn.getOutTradeNo());				
			}else if("B".equals(abr.getMerchantTransaction().getType())){
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}else{
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}
			barcodeRequest4AlipayTreeMap.put("service", AlipayPartnerConstants.SERVICE_REVERSE);
		}else if(abr instanceof AlipayBarcodeRefundRequest){
			// Operation parameter
			barcodeRequest4AlipayTreeMap.put("alipay_seller_id", AlipayPartnerConstants.PARTNER_ID);
			if("Q".equals(abr.getMerchantTransaction().getType())){
				AlipayQRCodeNotification aqrn = alipayBarcodeService.findAlipayQRCodeNotificationByMTId(abr.getMerchantTransaction().getId());
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", aqrn.getOutTradeNo());				
			}else if("B".equals(abr.getMerchantTransaction().getType())){
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}else{
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}
			barcodeRequest4AlipayTreeMap.put("service", AlipayPartnerConstants.SERVICE_REFUND);
			AlipayBarcodeRefundRequest abrr = (AlipayBarcodeRefundRequest)abr;
			barcodeRequest4AlipayTreeMap.put("currency", abrr.getCurrency());
			barcodeRequest4AlipayTreeMap.put("refund_amount", abrr.getRefundAmount().toEngineeringString());
			barcodeRequest4AlipayTreeMap.put("partner_refund_id", abrr.getPartnerRefundId().toString());
		}else if(abr instanceof AlipayQRCodeCreateRequest){
			AlipayQRCodeCreateRequest abrr = (AlipayQRCodeCreateRequest)abr;
			barcodeRequest4AlipayTreeMap.put("service", AlipayPartnerConstants.SERVICE_CREATE_QRCODE);
			barcodeRequest4AlipayTreeMap.put("biz_type", AlipayPartnerConstants.CREATE_QRCODE_BIZ_TYPE);
			barcodeRequest4AlipayTreeMap.put("biz_data", makeQRCodeCreateBizData(abrr.getMerchant()));
			barcodeRequest4AlipayTreeMap.put("notify_url", AlipayPartnerConstants.NOTIFY_URL);
		}else if(abr instanceof AlipayBarcodeQueryRequest){
			// Operation parameter
			if("Q".equals(abr.getMerchantTransaction().getType())){
				AlipayQRCodeNotification aqrn = alipayBarcodeService.findAlipayQRCodeNotificationByMTId(abr.getMerchantTransaction().getId());
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", aqrn.getOutTradeNo());				
			}else if("B".equals(abr.getMerchantTransaction().getType())){
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}else{
				barcodeRequest4AlipayTreeMap.put("partner_trans_id", abr.getMerchantTransaction().getId().toString());
			}
			barcodeRequest4AlipayTreeMap.put("service", AlipayPartnerConstants.SERVICE_QUERY);
		}
		
		return barcodeRequest4AlipayTreeMap;
	}
	
	public static boolean isMerchantTransactionSuccessPaid(List<AlipayBarcodePaymentRequest> abrList){
		boolean isSuccessPaid = false;
		for(AlipayBarcodePaymentRequest abpr:abrList){
			if("S".equals(abpr.getStatus())){
				isSuccessPaid = true;
				break;
			}else{
				isSuccessPaid = false;
			}
		}
		
		return isSuccessPaid;	
	}
	
	public static boolean isMerchantTransactionInUnkownStatus(List<AlipayBarcodePaymentRequest> abrList){
		boolean isSuccessPaid = false;
		for(AlipayBarcodePaymentRequest abpr:abrList){
			if("U".equals(abpr.getStatus())){
				isSuccessPaid = true;
				break;
			}else{
				isSuccessPaid = false;
			}
		}
		
		return isSuccessPaid;	
	}
	
	public static boolean isPaymentCanBeReversed(AlipayBarcodePaymentRequest abpr){
		boolean returnFlag = false;
		if(MerchantTransactionUtil.isMerchantTransactionCanBeReversed(abpr.getMerchantTransaction())){
			returnFlag = true;
		}
		return returnFlag;
	}
	public static boolean isPaymentCanBeCanceled(MerchantTransaction mt){
		boolean returnFlag = false;
		if(MerchantTransactionUtil.isMerchantTransactionCanBeCancelled(mt)){
			returnFlag = true;
		}
		return returnFlag;
	}
	public static boolean isPaymentCanBeRefunded(MerchantTransaction mt){
		boolean returnFlag = false;
		if(MerchantTransactionUtil.isMerchantTransactionCanBeRefund(mt)){
			returnFlag = true;
		}
		return returnFlag;
	}
	
	private static String makePaymentReqestExtendInfo(MerchantTransaction mt){
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"merchant_name\":");
		sb.append("\""+mt.getMerchant().getDisplayName()+"\"");
		sb.append("}");
		return sb.toString();
	}
	
	private static String makeQRCodeCreateBizData(MerchantInfo mi){
		StringBuffer sb = new StringBuffer();
		sb.append("{");
		sb.append("\"secondary_merchant_industry\":");
		sb.append("\""+MerchantInfoUtil.getSecondaryMerchantIndustry(mi)+"\",");
		sb.append("\"secondary_merchant_id\":");
		sb.append("\""+mi.getId()+"\",");
		sb.append("\"secondary_merchant_name\":");
		sb.append("\""+mi.getMerchantName()+"\",");
		//TODO
		//sb.append("\"notify_alipay_account\":");
		//sb.append("\""+mi.getAlipayAccount()+"\",");
		sb.append("\"trans_currency\":");
		sb.append("\""+mi.getDefaultCurrency()+"\",");
		sb.append("\"currency\":");
		sb.append("\""+mi.getDefaultCurrency()+"\"");
		sb.append("}");
		return sb.toString();
	}
}